package com.blog.servelt;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blog.bean.UserBean;
import com.blog.dao.UserDao;
import com.blog.service.BlogService;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class LoginServelt extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BlogService blogService;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServelt() {
        super();
        blogService = new BlogService();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().println("Welcome");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		UserDao userDao = blogService.getUserDao();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		UserBean user = userDao.login(username, password);
		
		
		response.setCharacterEncoding("utf-8");
		if(user != null){
			request.getSession().setAttribute("isLogin", true);
			request.getSession().setAttribute("username", user.getUsername());
			request.getSession().setAttribute("userId", user.getId());
			response.sendRedirect("blogManager/index.jsp");
		}else{
			System.out.println("LoginServelt.doPost()");
			request.getSession().setAttribute("Login", false);
			response.sendRedirect("login");
			
		}
		
	}
}
